package com.smxy.mall.controller;

import cn.hutool.extra.emoji.EmojiUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.smxy.mall.common.Response;
import com.smxy.mall.entity.User;
import com.smxy.mall.service.UserService;
import com.smxy.mall.utils.AES;
import com.smxy.mall.utils.HttpClientUtil;
import com.smxy.mall.utils.Token;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.DateFormat;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "微信模块")
@RestController
@Transactional(rollbackFor = Exception.class)
public class WxController {
    private final String AppID = "wxb243198059506b2b";
    private final String AppSecret = "fe6483f41cdadd9e232e808ce7b914c8";
    private final String SessionUrl = "https://api.weixin.qq.com/sns/jscode2session";

    @Resource
    private UserService userService;

    @ApiOperation("微信授权")
    @PostMapping(value = "/user/wxLogin")
    public Object wxLogin(@RequestParam("code")String code,@RequestParam("iv")String iv,@RequestParam("encryptedData")String encryptedData){
        String url = SessionUrl+"?appid=" + AppID + "&secret=" + AppSecret + "&js_code=" + code + "&grant_type=authorization_code";
        Map<String, String> param = new HashMap<>();
        param.put("appid", AppID);
        param.put("secret", AppSecret);
        param.put("js_code", code);
        param.put("grant_type", "authorization_code");
        String wxResult = HttpClientUtil.doGet(SessionUrl, param);
        JSONObject jsonObject = JSONObject.parseObject(wxResult);
        // 获取参数返回的
        String session_key = jsonObject.get("session_key").toString();
        String open_id = jsonObject.get("openid").toString();
        if(session_key.isEmpty()){
            return Response.fail(wxResult);
        }
        User obj = userService.findByOpenId(open_id);
        if(!StringUtils.isEmpty(obj)){
            return Response.success(obj);
        }else{
            String userInfo = null;
            JSONObject userInfoJSON = null;
            try {
                byte[] resultByte = AES.decrypt(Base64.decodeBase64(encryptedData),
                        Base64.decodeBase64(session_key),
                        Base64.decodeBase64(iv));
                userInfo = new String(resultByte, "UTF-8");
                userInfoJSON = JSON.parseObject(userInfo);
                User result = userService.wxSave(userInfoJSON);
                String token = Token.setToken(result.getId());
                Map<String,Object> map = new HashMap();
                map.put("token",token);
                map.put("userInfo",result);
                return Response.success(map);
            } catch (Exception e) {
                e.printStackTrace();
                return Response.fail("解密失败");
            }
        }
    }
}
